//
//  RTComposeCollectionView.swift
//  Weibo
//
//  Created by Brisinga on 16/3/14.
//  Copyright © 2016年 Root. All rights reserved.
//

import UIKit

class RTComposeCollectionView: UICollectionView {
    
    var composeCollectionCourse: ((collection: RTComposeCollectionView)->())?
    
    private var identifier = "pictureCell"
    
    // 图片数组
    private lazy var imageArr: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: layout)
        
        
        // 初始化内部组件
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    // 初始化内部组件
    private func setupUI() {
        
        backgroundColor = UIColor.clearColor()
        
        hidden = true
        
        self.delegate = self
        self.dataSource = self
        
        self.registerClass(RTComposeCell.self, forCellWithReuseIdentifier: identifier)
    }
    
    
    
    // 添加图片
    func addImage(image: UIImage) {
    
        imageArr.append(image)
        
        hidden = false
        
        self.reloadData()
    }
    
    // 布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let itemMargin: CGFloat = 5
        let itemWH: CGFloat = CGFloat(Int((self.frame.width - 2 * itemMargin)/3))
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: itemWH, height: itemWH)
        
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
    }
    
}


extension RTComposeCollectionView: UICollectionViewDataSource,UICollectionViewDelegate {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let imageCount = imageArr.count
        
        return (imageCount == 0 || imageCount == 9) ? imageCount : imageCount + 1
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! RTComposeCell
        
        if indexPath.item == imageArr.count {
        
            cell.image = nil
            
        }else {
            
            cell.image = imageArr[indexPath.item]
        
        }
        
        cell.deleteBtnCourse = { [weak self] (cell: RTComposeCell) in

            if let index = self?.indexPathForCell(cell) {
            
                self?.imageArr.removeAtIndex(index.item)
                
                self?.reloadData()
            }

        }
        
        return cell
    }
    
    // 点击方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
        if indexPath.item == imageArr.count {
        
            composeCollectionCourse?(collection: self)
        }
    }

}


private class RTComposeCell: UICollectionViewCell {
    
    var deleteBtnCourse: ((cell: RTComposeCell)->())?
    
    var image: UIImage? {
    
        didSet {
            
            deleteBtn.hidden = image == nil
            if image == nil {
            
                // 设置成加号按钮
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            
            }else {
            
                imageView.image = image
                imageView.highlightedImage = image
            }
        }
    }
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        // 加载内部组件
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // 加载内部组件
    private func setupUI() {
    
        contentView.addSubview(imageView)
        contentView.addSubview(deleteBtn)
        
        imageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            
            make.top.trailing.equalTo(imageView)
        }
        
    }
    
    
    @objc private func deleteBtnDidClick(btn: UIButton) {
    
        deleteBtnCourse?(cell:self)
    
    }
    
    
    // 懒加载
    private lazy var imageView: UIImageView = {
    
        let imageView = UIImageView()
        
        imageView.contentMode = .ScaleAspectFill
        
        imageView.clipsToBounds = true
        
        return imageView
    }()
    
    
    private lazy var deleteBtn: UIButton = {
    
        let btn = UIButton()
        
        // 添加点击事件
        btn.addTarget(self, action: "deleteBtnDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        return btn
        
    }()
    

}
